package cn.holy.app.xcddt.net

import cn.holy.app.xcddt.app.App
import cn.holy.app.xcddt.domain.net.ApiResponse
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Interceptor
import okhttp3.Response
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.concurrent.TimeUnit


/**
 * Created by 69568 on 2018/3/4.
 */
class TokenInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain?): Response {
        val originalRequest = chain?.request()
        val authorised = originalRequest?.newBuilder()//获取请求
        //这里就是说判读我们的网络条件，要是有网络的话我么就直接获取网络上面的数据，要是没有网络的话我么就去缓存里面取数据
        var token = App.sharedPreferences.getString("token", "")
        if (token != "") {
            authorised?.addHeader("Authorization", "Bearer $token")
            val response = chain!!.proceed(authorised!!.build())
            if (response.code() === 401) {//返回为token失效
//                token = refreshToken()//重新获取token，此处的刷新token需要同步执行以防止异步到来的问题
//                val newRequest = originalRequest.newBuilder()
//                        ?.header("Authorization", "Bearer $token")
//                        ?.build()//
//                return chain.proceed(newRequest)
                App.sharedPreferences.edit().putString("token", "")
                        .apply()
                Observable.timer(0, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({
                            App.userInfo = null
                            ARouter.getInstance().build("/app/login").navigation()
                        })

            }
            return response!!
        } else {
            return chain!!.proceed(authorised!!.build())
        }
    }

    private fun refreshToken(): String {
        val refreshTokenCall = ApiClient.webService.refreshToken()
        val token = refreshTokenCall.execute().body()

        val apiResponse = Gson().fromJson<ApiResponse<String>>(token, object : TypeToken<ApiResponse<String>>() {}.type)
        if (apiResponse.code == 200) {
            App.sharedPreferences.edit().putString("token", token).apply()
        }
        return token!!
    }

}